import * as constants from './constants';
import { fromJS } from 'immutable';
import {deleteNode, addNode, getAllNodes, changeNodeAvailability} from '../../../../api/config'
import {message} from 'antd'

const changeNodeData = (nodeData) => ({
    type: constants.GETNODES,
    nodeData: fromJS(nodeData)
})

const resetData = ()=>({
    type: constants.RESETNODE
})

const changeButton = (buttonLoading)=>({
    type: constants.BUTTONLOADING,
    buttonLoading: fromJS(buttonLoading)
})

export const getNodes = () => {
  return(dispatch) => {
        getAllNodes().then(res=>{
            if(res){
                if(res.data.ok){
                    const nodeData = res.data.data
                    dispatch(changeNodeData(nodeData))
                }else{
                    message.error(res.data.msg)
                }
            }
        })
    }
}

export const deleteItem = (id) => {
    return (dispatch) => {
        deleteNode({ip: id}).then(res=>{
            if(res){
                if(res.data.ok){  
                    message.success('节点删除成功');
                    dispatch(getNodes())
                }else{
                    message.error(res.data.msg)
                }
            }
        })
    }
}

export const addItem = (params) => {
    return dispatch => {
        dispatch(changeButton(true))
        addNode(params).then(res=>{
            if(res){
                dispatch(changeButton(false))
                if(res.data.ok){
                    message.success('添加节点成功');
                    dispatch(getNodes());
                }else{
                    message.error(res.data.msg)
                }
            }
        })
    }
}

export const clearData = () => {
    return dispatch => {
        dispatch(resetData)
    }
}

export const changeNodeStatus = (id) => {
    return dispatch => {
        changeNodeAvailability({id}).then(res=>{
            if(res){
                if(res.data.ok){
                    message.success('修改成功');
                    dispatch(getNodes())
                }
            }
        })
    }
}

